package com.wp.targetOffer;

import java.util.Stack;

/**
 * Created by 王萍 on 2017/8/2 0002.
 */

/**
 * 输入一个链表，输出该链表中倒数第k个结点。
 * 测试：当传入的head为0时；当K超过链表总长度时；当k<=0时，都需要返回null
 */
public class 链表中倒数第K个节点 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        System.out.println(FindKthToTail2(node1, 2).val);
    }

    public static ListNode FindKthToTail(ListNode head, int k) {
        if (head == null) return null;
        if (k <= 0) return null;

        Stack<ListNode> stack = new Stack();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        ListNode result = null;
        for (int i = 0; i < k; i++) {
            if (stack.empty()) return null;
            result = stack.pop();
        }
        return result;
    }

    //test节点先向后移k-1步，然后test和result一起向后移，直到test在链表尾部。
    public static ListNode FindKthToTail2(ListNode head, int k) {
        if (k <= 0) return null;
        if (head == null) return null;
        ListNode result = head, test = head;
        for (int i = 0; i < k - 1; i++) {
            test = test.next;
            if (test == null) return null;   //若此时test为null，下面的test.next就会报空指针异常。
        }
        while (test.next != null) {
            test = test.next;
            result = result.next;
        }
        return result;
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
